package com.teamwe.movecard.controller;

import com.alibaba.fastjson.JSONObject;
import com.teamwe.movecard.domain.Result;
import com.teamwe.movecard.domain.User;
import com.teamwe.movecard.service.UserService;
import com.teamwe.movecard.util.WxTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    /**
     * 功能描述：用户登录，当用户登录成功时，返回状态码和SessionId
     * @param session
     * @return
     */
    @ApiOperation(value = "微信用户授权", notes = "解析用户敏感信息的加密字符串，获取到用户的openId")
    @PostMapping("/login")
    public Result login(@ApiParam(value = "临时登录凭证、用户加密信息和加密算法出初始向量",required = true) @RequestBody User user, HttpSession session){

        Result result = new Result();
        //取出临时登录凭证js_code，密文和初始向量
        String  js_code =  user.getJs_code();
        String  encryptedData =  user.getEncryptedData();
        String  iv =  user.getIv();
        //从微信后台获取sessionkey
        String sessionkey = null;
        try {
            sessionkey = WxTool.getSessionKey(js_code);
        } catch (Exception e) {
            result.setStatus(false);
            result.setDescribe(String.format("提供的参数无法获取微信的sessionkey！收到的参数为：js_code: %s, encryptedData: %s, iv: %s", js_code, encryptedData, iv));
            return result;
        }
        JSONObject userInfo = null;
        try{
            //解析用户信息
            userInfo = WxTool.getUserInfo(encryptedData, sessionkey, iv);
        } catch (Exception e) {
            result.setStatus(false);
            result.setDescribe(String.format("解析用户信息出错！收到的参数为：js_code: %s, encryptedData: %s, iv: %s", js_code, encryptedData, iv));
            return  result;
        }
        if (userInfo != null) {
            String avatarUrl = (String)userInfo.get("avatarUrl");
            String mpOpenId = (String)userInfo.get("openId");
            String nickName = (String)userInfo.get("nickName");
            if (avatarUrl != null && !avatarUrl.trim().equals("")) {
                user.setUserAvatarUrl(avatarUrl);
            }
            if (nickName != null && !nickName.trim().equals("")) {

                user.setNickName(nickName);
            }
            if (mpOpenId != null && !mpOpenId.trim().equals("")) {
                user.setMpOpenId(mpOpenId);
            }
            try {
                userService.save(user);
                String describe = String.format("授权成功！收到的参数为：js_code: %s, encryptedData: %s, iv: %s", js_code, encryptedData, iv);
                log.info(describe);
                result.setStatus(true);
                result.addParam("mpOpenId", user.getMpOpenId());
                result.addParam("sessionId", session.getId());
                result.setDescribe(describe);
                return result;
            } catch (Exception e) {
                log.info("保存用户信息出错");
                result.setStatus(false);
                result.setDescribe(String.format("保存用户信息失败！收到的参数为：js_code: %s, encryptedData: %s, iv: %s", js_code, encryptedData, iv));
                return result;
            }
        }
        return result;
    }
}
